#include <principal.h>

using namespace Gtk::Menu_Helpers;/**<*/

MENU::MENU()
	{
	string aux;
	janela = 0;
	aux.clear();
	aux.append(IMG);
	aux += "cadeado.ico";
	icone = Gdk::Pixbuf::create_from_file (aux);
	Login = new Gtk::Window();
	Login->set_icon (icone);
	Login->signal_hide().connect(sigc::bind<Gtk::Window *>(sigc::mem_fun(*this,&MENU::sair),Login));
	Login->set_title(Glib::ustring("..::SCO - Login::.."));
	Login->set_icon(icone);
	Login->set_position(Gtk::WIN_POS_CENTER);
	Login->set_size_request (270,125);
	Login->set_type_hint(Gdk::WINDOW_TYPE_HINT_DIALOG);
	Tela = new Gtk::Fixed();
	Laux = new Gtk::Label(Glib::ustring("Usuário: "));
	Tela->put(*Laux,15,10);
	Usuario = new Gtk::Entry();
	Usuario->set_max_length (12);
	Usuario->signal_changed ().connect(sigc::bind<Gtk::Entry *>(sigc::mem_fun(*this,&MENU::minusculo),Usuario));
	Tela->put(*Usuario, 90, 5);
	Laux = new Gtk::Label(Glib::ustring("Senha: "));
	Tela->put(*Laux,15,47);
	Senha = new Gtk::Entry();
	Senha->set_max_length (8);
	Senha->set_visibility (false);
	Senha->set_invisible_char ('*');
	Usuario->signal_activate().connect(sigc::bind<Gtk::Window *, Gtk::Widget *>(sigc::mem_fun(*this,&MENU::setar_foco),Login,Senha));
	Tela->put(*Senha, 90, 42);
	L_OK = new Gtk::Button(Gtk::Stock::OK);
	Senha->signal_activate().connect(sigc::bind<Gtk::Window *, Gtk::Widget *>(sigc::mem_fun(*this,&MENU::setar_foco),Login,L_OK));
	L_OK->set_size_request (120,-1);
	L_OK->signal_clicked ().connect(sigc::mem_fun(*this,&MENU::checar_login));
	Tela->put(*L_OK, 10, 84);
	L_Cancel = new Gtk::Button(Gtk::Stock::CANCEL);
	L_Cancel->set_size_request (120,-1);
	L_Cancel->signal_clicked ().connect(sigc::bind<Gtk::Window *>(sigc::mem_fun(*this,&MENU::sair),Login));
	Tela->put(*L_Cancel, 140, 84);
	Login->add(*Tela);
	Login->set_focus(*Usuario);
	Login->show_all();
	}

MENU::~MENU()
	{
	}

void MENU::sair(Gtk::Window *w)
	{
	w->hide();
	}

void MENU::setar_foco(Gtk::Window *j, Gtk::Widget *w)
	{
	j->set_focus(*w);
	}

void MENU::maiusculo(Gtk::Entry *e)
	{
	string aux;
	aux.clear();

	aux = e->get_text();
	aux = ParaMaiusculos(aux);
	e->set_text(aux);
	}

void MENU::minusculo(Gtk::Entry *e)
	{
	string aux;
	aux.clear();

	aux = e->get_text();
	aux = ParaMinusculos(aux);
	e->set_text(aux);
	}

bool MENU::relogio()
	{
	string status;
	status.clear();
	status = "Desenvolvido por Sombra® - ";
	status.append(data_formatada(hoje(),2));
	status += " - ";
	status.append(agora());
	status += " - Usuário: "+u_nome;
	statusbar = BarraStatus->push(Glib::ustring(status));
	return true;
	}
void MENU::checar_login ()
	{
	BANCOPG *login;
	int codigo, i, j;
	char *aux;
	string AUX;
	vector<string> linha, campos, valores, tabelas;
	bool logado;
	unsigned char c_senha[MD5_DIGEST_LENGTH];
	const unsigned char *str;
	char *senha_cifrada;
	
	AUX.clear();
	AUX = Senha->get_text();
	str = new char[AUX.length()+1];
	strcpy(str,AUX.c_str());
	MD5(str,strlen(str),c_senha);
	delete str;
	senha_cifrada = new char[33];
	senha_cifrada[0] = '\0';
	for (i=0,j=0; i < MD5_DIGEST_LENGTH; i++,j=+2)
		{
		aux = new char[3];
		sprintf(aux,"%02x",(unsigned int)c_senha[i]);
		strcat(senha_cifrada,aux);
		delete aux;
		}
	logado = false;
	banco = new BD();
	banco->acao = 1;
	campos.clear();
	AUX.clear();
	AUX = "id_user";
	campos.push_back (AUX);
	AUX.clear();
	AUX = "nome";
	campos.push_back (AUX);
	AUX.clear();
	AUX = "e_mail";
	campos.push_back (AUX);
	AUX.clear();
	AUX = "usuario";
	campos.push_back (AUX);
	AUX.clear();
	AUX = "nivel";
	campos.push_back (AUX);
	AUX.clear();
	AUX = "entidade";
	campos.push_back (AUX);
	banco->campos = campos;
	tabelas.clear();
	AUX.clear();
	AUX = "cadastro.usuario";
	tabelas.push_back (AUX);
	banco->tabelas = tabelas;
	valores.clear();
	AUX.clear();
	AUX = " where usuario='"+Usuario->get_text()+"' and senha='";
	AUX.append(senha_cifrada);
	AUX += "'";
	valores.push_back (AUX);
	banco->valores = valores;
	banco->acionar();
	if (banco->query_result != 3)
		{
		if (banco->registros > 0)
			{
			logado = true;
			linha = banco->resultou.at(0);
			codigo = atoi(linha.at(0).c_str());
			u_codigo = codigo;
			u_nome.clear();
			u_nome = linha.at(1);
			//id_user,nome,e_mail,usuario,senha,nivel,entidade
			u_email.clear();
			u_email = linha.at(2);
			u_usuario.clear();
			u_usuario = linha.at(3);
			u_senha.clear();
			u_senha = linha.at(4);
			codigo = atoi(linha.at(5).c_str());
			u_nivel = codigo;
			if (u_nivel > 0)
				{
				codigo = atoi(linha.at(6).c_str());
				u_ligacao = codigo;
				}
			}				
		}
	if (logado)
		{
		Gtk::MessageDialog dialog(*Login,Glib::ustring("Acesso Garantido"), false, Gtk::MESSAGE_INFO);
		AUX.clear();
		AUX = u_nome + "!\nBem vindo ao SCO!";
		dialog.set_secondary_text(Glib::ustring(AUX));
		dialog.run();
		Login->hide();
		dialog.hide();
		AUX.clear();
		AUX.append(IMG);
		AUX += "sco.ico";
		icone = Gdk::Pixbuf::create_from_file (AUX);
		janela = 1;
		carregar_janela();
		}
	else
		{
		Gtk::MessageDialog dialog(*Login, Glib::ustring("Falha na autenticação"), false, Gtk::MESSAGE_ERROR);
		dialog.set_secondary_text(Glib::ustring("Verifique seu Login/Senha e tente novamente!"));
		dialog.run();
		//Usuario->set_text("");
		Senha->set_text("");
		Login->set_focus(*Usuario);
		delete banco;
		}
	}

void MENU::carregar_janela()
	{
	switch(janela)
		{
		case 1:
			{
			Principal = new Gtk::Window();
			Principal->set_title (Glib::ustring("SCO - Consultoria OnLine: Controle: Saúde e Segurança no Trabalho / Alvarás / Licenças"));
			Principal->set_icon(icone);
			Principal->set_position(Gtk::WIN_POS_CENTER);
			Principal->maximize ();
			Principal->signal_hide().connect(sigc::bind<Gtk::Window *>(sigc::mem_fun(*this,&MENU::sair),Principal));
			VPrincipal = new Gtk::VBox(false,0);
			VMenu = new Gtk::VBox();
			montar_menu();
			VPrincipal->pack_start(*VMenu,false,false,0);
			VStatus = new Gtk::VBox(false,0);
			BarraStatus = new Gtk::Statusbar ();
			statusbar = BarraStatus->push(Glib::ustring("Desenvolvido por Sombra®"));
			VStatus->pack_end(*BarraStatus,false,false,0);
			Glib::signal_timeout().connect(sigc::mem_fun(*this,&MENU::relogio), 1000);
			VPrincipal->pack_end(*VStatus,false,false,0);
			Principal->add(*VPrincipal);
			Principal->show_all();
			Gtk::Main::run(*Principal);
			break;
			}
		}
	}

void MENU::montar_menu()
	{
	//Iniciando menu
	menu = Gtk::manage(new Gtk::MenuBar());
	VMenu->pack_start(*menu,true,true,0);
	//Menu Arquivo->Configurações
		{
		MenuConfig = Gtk::manage(new Gtk::Menu());
		Gtk::Menu::MenuList& menulist = MenuConfig->items();
		menulist.push_back(MenuElem(Glib::ustring("_Configurações Gerais"),Gtk::AccelKey("<contro>F"),sigc::mem_fun(*this,&MENU::config)));
		menulist.push_back(MenuElem(Glib::ustring("_Logs Acesso"),Gtk::AccelKey("<contro>H"),sigc::mem_fun(*this,&MENU::logs)));
		}
	//Menu Arquivo
		{
		MenuArquivo = Gtk::manage(new Gtk::Menu());
		Gtk::Menu::MenuList& menulist = MenuArquivo->items();
		if (u_nivel <= 1)
			{
			menulist.push_back(MenuElem(Glib::ustring("_Configurações"),*MenuConfig));
			menulist.push_back(SeparatorElem());
			}
		menulist.push_back(MenuElem(Glib::ustring("_Sair"),Gtk::AccelKey("<alt><F4>"),sigc::bind<Gtk::Window*>(sigc::mem_fun(*this, &MENU::sair),Principal)));
		}
	menu->items().push_back(MenuElem(Glib::ustring("_Arquivo"),Gtk::AccelKey("<alt>A"),*MenuArquivo));
	}

void MENU::config()
	{
	}

void MENU::logs()
	{
	}